<template>
  <doc-alert
    title="【库存】库存调拨、库存盘点"
    url="https://doc.iocoder.cn/erp/stock-move-check/"
  />

  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="名称" prop="name">
        <el-select
          v-model="queryParams.id"
          clearable
          :filter-method="hospitalFilter"
          filterable
          placeholder="请选择产品名称"
          class="!w-240px"
        >
          <el-option
            v-for="item in supplierList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="分类" prop="categoryId">
        <el-tree-select
          v-model="queryParams.categoryId"
          :data="categoryList"
          :props="defaultProps"
          check-strictly
          default-expand-all
          placeholder="请输入分类"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="单位" prop="unitId">
        <el-tree-select
          v-model="queryParams.unitId"
          :data="unitList"
          :props="defaultProps"
          check-strictly
          default-expand-all
          placeholder="请输入单位"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="生产厂家" prop="manufacturer">
        <el-input
          v-model="queryParams.manufacturer"
          placeholder="请输入生产厂家"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="是否带量" prop="isQuantity">
        <el-select
          v-model="queryParams.isQuantity"
          placeholder="请选择是否带量"
          clearable
          class="!w-240px"
        >
        <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.ERP_IS_QUANTITY)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否收费" prop="isFree">
        <el-select
          v-model="queryParams.isFree"
          placeholder="请选择是否收费"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.IS_FREE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="专机专用" prop="isDedicated">
        <el-select
          v-model="queryParams.isDedicated"
          placeholder="请选择是否专机专用"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.IS_DEDICATED)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="注册证号" prop="registCertNum">
        <el-input
          v-model="queryParams.registCertNum"
          placeholder="请输入注册证号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="医保编码" prop="medicalInsurCode">
        <el-input
          v-model="queryParams.medicalInsurCode"
          placeholder="请输入医保27位编码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['spd:product:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['spd:product:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="条码" align="center" prop="barCode" width="200%"/>
      <el-table-column label="名称" align="center" prop="name" width="200%"/>
      <el-table-column label="规格" align="center" prop="standard" width="100%"/>
      <el-table-column label="分类" align="center" prop="categoryName" />
      <el-table-column label="单位" align="center" prop="unitName" />
      <el-table-column label="生产厂家" align="center" prop="manufacturer" width="200%"/>
      <el-table-column label="是否收费" align="center" prop="isFree"  >
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.IS_FREE" :value="scope.row.isFree" />
        </template>
      </el-table-column>
      <el-table-column label="专机专用" align="center" prop="isDedicated"  width="150%">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.IS_DEDICATED" :value="scope.row.isDedicated" />
        </template>
      </el-table-column>
      <el-table-column label="注册证号" align="center" prop="registCertNum" />
      <el-table-column label="医保编码" align="center" prop="medicalInsurCode" width="300%"/>
      <el-table-column
        label="采购价格"
        align="center"
        prop="purchasePrice"
        :formatter="erpPriceTableColumnFormatter"
         width="100px"
      />
      <el-table-column
        label="销售价格"
        align="center"
        prop="salePrice"
        :formatter="erpPriceTableColumnFormatter"
         width="100px"
      />
      <el-table-column
        label="最低价格"
        align="center"
        prop="minPrice"
        :formatter="erpPriceTableColumnFormatter"
        width="100px"
      />
      <el-table-column label="状态" align="center" prop="status"  >
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>

      <el-table-column label="是否带量" align="center" prop="isQuantity"  width="150%">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.ERP_IS_QUANTITY" :value="scope.row.isQuantity" />
        </template>
      </el-table-column>

      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" width="200%">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['spd:product:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['spd:product:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <StockMoveForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter,dateFormatter2 } from '@/utils/formatTime'
import download from '@/utils/download'

import { StockMoveApi, StockMoveVO } from '@/api/erp/stock/move'
import StockMoveForm from './StockMoveForm.vue'
import { ProductApi, ProductVO } from '@/api/erp/product/product'
import { WarehouseApi, WarehouseVO } from '@/api/erp/stock/warehouse'
import { ProductCategoryApi, ProductCategoryVO } from '@/api/spd/product/category'
import { ProductUnitApi, ProductUnitVO } from '@/api/spd/product/unit'
import { UserVO } from '@/api/system/user'
import * as UserApi from '@/api/system/user'
import { erpCountTableColumnFormatter, erpPriceTableColumnFormatter } from '@/utils'
import { defaultProps, handleTree } from '@/utils/tree'

/** ERP 库存调度单列表 */
defineOptions({ name: 'ErpStockMove' })
const categoryList = ref<ProductCategoryVO[]>([]) // 产品分类列表
const unitList = ref<ProductUnitVO[]>([])//单位列表
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const supplierList = ref<ProductVO[]>([])  // 供应商列表
  let porductList= [] // 医院列表
const loading = ref(true) // 列表的加载中
const list = ref<StockMoveVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  no: undefined,
  productId: undefined,
  fromWarehouseId: undefined,
  moveTime: [],
  status: undefined,
  remark: undefined,

  creator: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const productList = ref<ProductVO[]>([]) // 产品列表
const warehouseList = ref<WarehouseVO[]>([]) // 仓库列表
const userList = ref<UserVO[]>([]) // 用户列表

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ProductApi.getProductPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}


/**
 * 筛选产品
 */
 const hospitalFilter =(v)=> {
  // v为input输入的模糊查询项
  supplierList.value = porductList.filter((item) => {
   // 确保item.name不是null或undefined
    const name = item.name || '';
    const fullPinyin = item.fullPinyin || '';
    const firstPinyin = item.firstPinyin || '';
    const wubiShortcode = item.wubiShortcode || '';
    // 如果直接包含输入值直接返回true
        // 如果直接包含输入值直接返回true
        if (
          name.indexOf(v) !== -1 ||
          // toUpperCase 英文字母转换大小写   toLowerCase()以确保大小写不敏感的比较，这里进行了统一的转换为小写进行比较。
          fullPinyin.toLowerCase().indexOf(v.toLowerCase()) !== -1 ||
          firstPinyin.toLowerCase().indexOf(v.toLowerCase()) !== -1||
          wubiShortcode.toLowerCase().indexOf(v.toLowerCase()) !== -1
    ) {
      return true;
    }
    return false;
    
  });
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (ids: number[]) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await StockMoveApi.deleteStockMove(ids)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
    selectionList.value = selectionList.value.filter((item) => !ids.includes(item.id))
  } catch {}
}

/** 审批/反审批操作 */
const handleUpdateStatus = async (id: number, status: number) => {
  try {
    // 审批的二次确认
    await message.confirm(`确定${status === 20 ? '审批' : '反审批'}该调度单吗？`)
    // 发起审批
    await StockMoveApi.updateStockMoveStatus(id, status)
    message.success(`${status === 20 ? '审批' : '反审批'}成功`)
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await StockMoveApi.exportStockMove(queryParams)
    download.excel(data, '库存调度单.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 选中操作 */
const selectionList = ref<StockMoveVO[]>([])
const handleSelectionChange = (rows: StockMoveVO[]) => {
  selectionList.value = rows
}

/** 初始化 **/
onMounted(async () => {
  await getList()
  // 加载产品、仓库列表、客户
  // 产品分类
  const categoryData = await ProductCategoryApi.getProductCategorySimpleList()
  categoryList.value = handleTree(categoryData, 'id', 'parentId')
  // 产品单位
  const unitData = await ProductUnitApi.getProductUnitSimpleList()
  unitList.value = handleTree(unitData, 'id')
  const supplierData = await ProductApi.getProductSimpleList()
  supplierList.value = handleTree(supplierData, 'id')
  porductList = Object.assign(supplierData);
})
// TODO 芋艿：可优化功能：列表界面，支持导入
// TODO 芋艿：可优化功能：详情界面，支持打印
</script>
